;(function ($,window,document,undefined ){
    //配置参数
    var defaults = {
        title:'请选择设备',
        root:null,//根路径
        callback:function(){}	//回调
    };

    var Hospital = function(element,options){
        //全局变量
        var opts = options,//配置
            $document = $(document),
            $obj = $(element);//容器

        this.getSelectedData = function(){
            return opts.json;
        }

        this.queryProvince = function (){
            $obj.find("select[name='provinceId']").html("");
            publicAjax(opts.root+"/base/queryProvince","POST",{},function (data){
                var html = "";
                if(data.ret == 200){
                    $.each(data.data,function (index,item){
                        html+="<option value='"+item.provinceId+"'>"+item.province+"</option>";
                    })
                    $obj.find("select[name='provinceId']").html(html);
                    $obj.find("select[name='provinceId']").val(null).trigger("change");

                }else{
                    flavrShowByTime(data.msg,null,"danger",false);
                }
            })

        }

        this.changProvince = function (){
                var provinceId = $obj.find("select[name='provinceId']").val();
                if(provinceId == null  || provinceId == ""){
                    $obj.find("select[name='cityId']").html("");
                    return;
                }

            $obj.find("select[name='cityId']").html("");
            publicAjax(opts.root+"/base/queryCity","POST",{},function (data){
                var html = "";
                if(data.ret == 200){
                    $.each(data.data,function (index,item){
                        html+="<option value='"+item.cityId+"'>"+item.city+"</option>";
                    })
                    $obj.find("select[name='cityId']").html(html);
                    $obj.find("select[name='cityId']").val(null).trigger("change");

                }else{
                    flavrShowByTime(data.msg,null,"danger",false);
                }
            })

        }


        var map = new Map();

        this.bindHospitalData = function (deviceList){
            $obj.find("[name='hospitalList']").html("");
            var str = "";
            $.each(deviceList,function (index,item) {
                str+="<tr>"
                    +'<td class="text-center text-muted"><input type="checkbox" class="flat-green" name="aaa" value="'+item.hospitalId+'"></td>'
                    +'<td class="text-center text-muted">'+(item.hospitalName==null?'':item.hospitalName)+'</td>'
                    +'<td class="text-center text-muted">'+(item.hospitalCode==null?'':item.hospitalCode)+'</td>'
                    +'<td class="text-center text-muted">'+(item.region==null?'':item.region)+'</td>'
                    +'<td class="text-center text-muted">'+(item.hospitalContacts==null?'':item.hospitalContacts)+'</td>'
                    +'<td class="text-center text-muted">'+(item.hospitalPhone==null?'':item.hospitalPhone)+'</td>'
                    +'<td class="text-center text-muted">'+(item.address==null?'':item.address)+'</td>'
                "</tr>";
                map.put(item.hospitalId,item);
            });
            $obj.find("[name='hospitalList']").html(str);

            $obj.find('input[type="checkbox"].flat-green, input[type="radio"].flat-red').iCheck({
                checkboxClass: 'icheckbox_flat-green',
                radioClass: 'iradio_flat-green'
            });
            $obj.find("input[name='aaa']").on('ifChecked', function(event){
                var current = $(this).parents("tr").index();
                $("[name='aaa']:checked").each(function(i){
                    if($(this).parents("tr").index()!=current){
                        $(this).iCheck('uncheck');
                    }
                });
            });
        }

        this.list = function(start,limit,obj,end){
            var object = this;
            var provinceId = $obj.find('select[name="provinceId"]').val();
            var allName = $obj.find('input[name="allName"]').val();
            var cityId = $obj.find('select[name="cityId"]').val();
            var json = { start:start,end:end,provinceId:provinceId,allName:allName,cityId:cityId};
            publicAjax(opts.root+"/hospital/queryHospitalList","POST",json,function (data){
                if(data.ret == 200){
                    object.bindHospitalData(data.data.list);
                    object.page(data.data.count,limit,(start/limit+1),object);
                }else{
                    flavrShowByTime(data.msg,null,"danger",false);
                }
            })
        }

        this.page = function(total,limit,current,obj){
            $('.device-page').empty();
            $('.device-page').pagination({
                totalData:total,
                showData:limit,//数据总数totalData和每页显示的条数showData必须同时配置，否则默认使用总页数pageCount;limit可选值 5 10 20 50
                //pageCount:50,
                current:current,
                jump:true,
                coping:true,
                homePage:'首页',
                endPage:'末页',
                prevContent:'上页',
                nextContent:'下页',
                callback:function(index){
                    /*start = (index.getCurrent()-1)*limit;
                     obj.list(start,limit);*/
                    limit = index.getShowData();
                    var end = (index.getCurrent()-1) * limit + limit;
                    obj.list((index.getCurrent()-1) * limit,limit,obj,end);
                }
            });
        }

        //绑定事件
        this.filling = function(opts){
            $obj.iziModal({
                title: opts.title,
                headerColor: '#00c0ef',
                theme: '',  // light
                attached: '', // bottom, top
                icon: null,
                iconText: null,
                iconColor: '',
                rtl: false,
                width: 1000,
                padding: 0,
                radius: 3,
                zindex: 9999,
                iframe: false,
                iframeHeight: 400,
                iframeURL: null,
                focusInput: false,
                group: '',
                loop: false,
                navigateCaption: true,
                navigateArrows: true, // closeToModal, closeScreenEdge
                history: true,
                restoreDefaultContent: false,
                autoOpen: true, // Boolean, Number
                bodyOverflow: false,
                fullscreen: true,
                openFullscreen: false,
                closeOnEscape: false,
                overlay: true,
                overlayClose: false,
                overlayColor: 'rgba(0, 0, 0, 0.4)',
                timeout: false,
                timeoutProgressbar: false,
                pauseOnHover: false,
                timeoutProgressbarColor: 'rgba(255,255,255,0.5)',
                transitionIn: 'comingIn',
                transitionOut: 'comingOut',
                transitionInOverlay: 'fadeIn',
                transitionOutOverlay: 'fadeOut',
                onFullscreen: function(){},
                onResize: function(){
                    //$obj.iziModal('recalculateLayout');
                },
                onOpening: function(){},
                onOpened: function(){},
                onClosing: function(){},
                onClosed: function(){}
            });
            var html = '<div class="box-body" style="margin:5px 0 -10px 0">'
                +  	'<div class="row">'
                +			'<div class="col-md-3">'
                +				'<div class="form-group" >'
                +					'<input type="text" class="form-control" name="allName" placeholder="医院编号/医院名称">'
                +      		'</div>'
                +      	'</div>'
                +			'<div class="col-md-3">'
                + 				'<div class="form-group" >'
                +					'<select id="provinceId" name="provinceId" class="form-control" style="width: 100%;">'
                +					'</select>'
                +      		'</div>'
                +      	'</div>'
                +			'<div class="col-md-3">'
                + 				'<div class="form-group" >'
                +					'<select id="cityId" name="cityId" class="form-control" style="width: 100%;">'
                +					'</select>'
                +      		'</div>'
                +      	'</div>'
                + 			'<div class="col-md-3 pull-right">'
                + 				'<div class="form-group pull-right">'
                + 					'<button name="search" type="button" class="btn btn-info btn-sm" style="margin-right:5px" data-toggle="tooltip" data-placement="bottom" title="">搜索</button>'
                + 					'<button name="select" type="button" class="btn btn-info btn-sm" data-toggle="tooltip" data-placement="bottom" title="">确定</button>'
                + 				'</div>'
                + 			'</div>'
                + 		'</div>'
                + '</div>';

//			html += '<div class="box-footer clearfix"><div class="M-box2 text-center device-page"></div></div>';

            html += '<div class="box-body no-padding table-responsive" style="max-height:400px;voerflow:auto">'
                +		'<table class="table table-hover table-condensed">'
                +           '<tbody>'
                +			'<tr class=info>'
                +				'<th style="width:35px">请选择</th>'
                +				'<th class="text-center text-muted">医院名称</th>'
                +				'<th class="text-center text-muted">医院编号</th>'
                +				'<th class="text-center text-muted">省份-城市-区域</th>'
                +				'<th class="text-center text-muted">医院联系人</th>'
                +				'<th class="text-center text-muted">联系人电话</th>'
                +				'<th class="text-center text-muted">地址</th>'
                +			'</tr>'
                +       '</tbody>'
                +       '<tfoot name="hospitalList"></tfoot>'

                +		'</table>'
                +	'</div>';

            html += '<div class="box-footer clearfix"><div class="M-box2 text-center device-page"></div></div>';

            $obj.find(".iziModal-content").html(html);

            $obj.find("select[name='provinceId']").select2({language:"zh-CN",placeholder: "请选择省份",allowClear: true});
            $obj.find("select[name='cityId']").select2({language:"zh-CN",placeholder: "请选择城市",allowClear: true});
            this.queryProvince();
            var obejct = this;
            $obj.find("select[name='provinceId']").change(function (){
                obejct.changProvince();
            });
            this.list(0,10,$obj,10);
        }

        //绑定事件
        this.eventBind = function(){

            var self = this;
            //必须先解绑再绑定事件，否则多次执行后会多次触发
            $obj.off('click','button[name="select"]').on('click','button[name="select"]',function(){
                var hospitalId = $obj.find("input[name='aaa']:checked").val();
                var hospital = map.get(hospitalId);
                opts.json = {hospitalId:hospital.hospitalId,hospitalName:hospital.hospitalName};
                $obj.iziModal('close');
                typeof opts.callback === 'function' && opts.callback(self);
            });

            //必须先解绑再绑定事件，否则多次执行后会多次触发
            $obj.off('click','button[name="search"]').on('click','button[name="search"]',function(){
                self.list(0,10,$obj,10);
            });
        }

        //初始化
        this.init = function(){
            this.filling(opts);
            this.eventBind();
        };
        this.init();
    }

    $.fn.hospital = function(parameter,callback){
        if(typeof parameter == 'function'){//重载
            callback = parameter;
            parameter = {};
        }else{
            parameter = parameter || {};
            callback = callback || function(){};
        }
        var options = $.extend({},defaults,parameter);
        callback(new Hospital(this, options));
    };
})(jQuery, window,document);